import json
import os
from datetime import datetime
from urllib.parse import unquote
from uuid import uuid4

from flask import request, redirect, flash, render_template, url_for, current_app
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.utils import secure_filename

from app import login_required_with_check_scope
from app.model.base import db
from app.model.user import User
from app.validator.auth import LoginForm, RegisterForm


def bind_app_route(app):
    @app.route('/', methods=['get'])
    def index_ep():
        return redirect(url_for('web.index_ep'))

    @app.route('/about', methods=['get'])
    def about_ep():
        return render_template('about.html')

    @app.route('/auth/login', methods=['GET', 'POST'])
    def login_ep():
        if current_user.is_authenticated:
            return redirect(url_for('web.index_ep'))
        form = LoginForm(request.values)
        if request.method == 'POST' and form.validate():
            user = User.query.filter_by(email=form.email.data, admin=form.admin.data).first()
            if user and user.check_password(form.password.data):
                login_user(user, remember=True)
                next_url = request.args.get('next')
                if not next_url or not next_url.startswith('/'):
                    next_url = url_for('web.index_ep')
                return redirect(next_url)
            else:
                flash('登录信息有误，请检查邮箱密码和用户类型')
        flash(form.errors, 'form')
        return render_template('auth/login.html', form=form)

    @app.route('/auth/register', methods=['GET', 'POST'])
    def register_ep():
        """
            用户注册

        :form:
            email: 注册邮箱
            password: 密码
            verify_password: 确认密码
            realname: 姓名
            address: 收货地址
            tel: 联系电话

        :return:
            success: 重定向到登录
            exception:  带上错误信息回到注册页面
        """
        if current_user.is_authenticated:
            return redirect(url_for('web.index_ep'))
        form = RegisterForm(request.values)
        if request.method == 'POST' and form.validate():  # 验证表单
            with db.auto_commit():  # 注册
                user = User()
                user.set_attrs(form.data)
                db.session.add(user)
            flash('注册成功')
            return redirect(url_for('login_ep'))
        flash(form.errors, 'form')
        return render_template('auth/register.html', form=form)

    @app.route('/auth/logout', methods=['GET'])
    @login_required
    def logout_ep():
        logout_user()
        return redirect(url_for('web.index_ep'))

    @app.route('/file_upload', methods=['POST'])
    def file_upload_ep():
        def is_allowed(s):
            return '.' in s and s.rsplit('.', 1)[1] in {'png', 'jpg', 'jpeg', 'gif', 'webp'}

        if 'file' not in request.files:
            return json.dumps(dict(msg='file is null', code=1000))
        file = request.files['file']
        filename = secure_filename(file.filename)

        if is_allowed(filename):
            filename = datetime.now().strftime("%Y%m%d%H%M%S") + '_' + str(uuid4()).replace('-', '') + '.' + \
                       filename.rsplit('.', 1)[1]
            save_filename = os.path.join(current_app.config['APP_INSTANCE_PATH'], 'app', 'static', 'upload', filename)
            file.save(save_filename)

            return json.dumps(dict(msg='ok', code=0, data=filename))
        return json.dumps(dict(msg='fail', code=1001))


if __name__ == '__main__':
    print('321321'[0])
